<template>
  <div>
    <!-- 工具栏 -->
    <div>
      <el-row>
        <el-col :span="8">
          <!-- 操作按钮 -->
          <div class="operation-div">
            <el-button type="primary" @click="onAssign">派单</el-button>
            <el-button type="primary" @click="onReceive">收单</el-button>
          </div>
        </el-col>
        <el-col :span="16">
          <!-- 条件查询 -->
          <div class="search-div">
            <el-form :inline="true" :model="searchData" class="demo-form-inline">
              <el-form-item label="业务名称：">
                <el-input v-model="searchData.businessName" placeholder="请输入业务名称" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button type="primary" @click="onReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 表格内容 -->
    <div>
      <el-table :data="tableData" border stripe style="width: 100%" :header-cell-style="{ background: '#ECF5FF' }">
        <el-table-column type="index" :index="indexMethod" />
        <el-table-column prop="businessId" label="业务编号" />
        <el-table-column prop="status" label="状态" />
        <el-table-column prop="dispatchTime" label="派单时间" />
        <el-table-column prop="returnTime" label="返单时间" />
        <el-table-column prop="operator" label="操作人" />
        <el-table-column prop="regionName" label="地区" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="margin-top: 20px">
        <el-pagination
          v-model:current-page="pageData.currentPage"
          v-model:page-size="pageData.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="->, jumper, total, sizes, prev, pager, next"
          :total="pageData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 派单对话框 -->
    <el-dialog v-model="assignDialogVisible" title="派单" width="500">
      <el-form :model="assignForm" ref="assignFormRef" :rules="assignRules">
        <el-form-item label="选择工单" prop="workOrderId">
          <el-select v-model="assignForm.workOrderId" placeholder="请选择工单">
            <el-option v-for="item in unassignedOrders" :key="item.workOrderId" :label="item.businessName" :value="item.workOrderId" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择人员" prop="operator">
          <el-select v-model="assignForm.operator" placeholder="请选择人员">
            <el-option v-for="person in operators" :key="person" :label="person" :value="person" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约安装时间" prop="dispatchTime">
          <el-date-picker v-model="assignForm.dispatchTime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onAssignConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 收单对话框 -->
    <el-dialog v-model="receiveDialogVisible" title="收单" width="500">
      <el-form :model="receiveForm" ref="receiveFormRef" :rules="receiveRules">
        <el-form-item label="选择工单" prop="workOrderId">
          <el-select v-model="receiveForm.workOrderId" placeholder="请选择工单">
            <el-option v-for="item in assignedOrders" :key="item.workOrderId" :label="item.businessName" :value="item.workOrderId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="receiveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onReceiveConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑工单" width="500">
      <el-form :model="editForm" ref="editFormRef" :rules="editRules">
        <el-form-item label="业务编号" prop="businessId">
          <el-input v-model="editForm.businessId" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="未派单" value="未派单" />
            <el-option label="已派单" value="已派单" />
            <el-option label="已收单" value="已收单" />
            <el-option label="已回单" value="已回单" />
          </el-select>
        </el-form-item>
        <el-form-item label="派单时间" prop="dispatchTime">
          <el-date-picker v-model="editForm.dispatchTime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="返单时间" prop="returnTime">
          <el-date-picker v-model="editForm.returnTime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item label="地区" prop="regionName">
          <el-input v-model="editForm.regionName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onEditConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getWorkOrders,
  assignWorkOrder,
  receiveWorkOrder,
  deleteWorkOrder,
  getUnassignedWorkOrders,
  getAssignedWorkOrders,
  getOperators,
  updateWorkOrder,
} from '@/api/workorder.js';

// 表单数据
const searchData = ref({
  businessName: ''
});

// 表格数据
const tableData = ref([]);

// 分页数据
const pageData = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 分页插件，每页条数发生改变时
const handleSizeChange = (val) => {
  pageData.pageSize = val;
  getPageList();
};

// 分页插件，当页码发生改变时
const handleCurrentChange = (val) => {
  pageData.currentPage = val;
  getPageList();
};

// 分页查询
const getPageList = async () => {
  const params = {
    pageSize: pageData.pageSize,
    currentPage: pageData.currentPage,
    businessName: searchData.value.businessName
  };
  const result = await getWorkOrders(params);
  pageData.total = result.data.total;
  tableData.value = result.data.items;
};

// 头部表单函数定义
const onSearch = () => {
  getPageList();
};

// 重置查询表单
const onReset = () => {
  searchData.value = '';
  getPageList();
};

// 添加修改对话框表单
const assignForm = ref({
  workOrderId: '',
  operator: '',
  dispatchTime: ''
});
const receiveForm = ref({
  workOrderId: ''
});

// 重置对话框表单
const resetAssignForm = () => {
  assignForm.value = {
    workOrderId: '',
    operator: '',
    dispatchTime: ''
  };
};
const resetReceiveForm = () => {
  receiveForm.value = {
    workOrderId: ''
  };
};

const assignDialogVisible = ref(false);
const receiveDialogVisible = ref(false);
const editDialogVisible = ref(false);
const operators = ref([]);
const unassignedOrders = ref([]);
const assignedOrders = ref([]);

// 派单按钮事件
const onAssign = async () => {
  assignDialogVisible.value = true;
  const unassignedResult = await getUnassignedWorkOrders({
    pageSize: 10,
    currentPage: 1
  });
  unassignedOrders.value = unassignedResult.data.items;
  const operatorsResult = await getOperators();
  operators.value = operatorsResult.data;
};

// 收单按钮事件
const onReceive = async () => {
  receiveDialogVisible.value = true;
  const assignedResult = await getAssignedWorkOrders({
    pageSize: 10,
    currentPage: 1
  });
  assignedOrders.value = assignedResult.data.items;
};

// 提交派单对话框表单按钮事件
const onAssignConfirm = async () => {
  if (!assignFormRef.value) return;
  await assignFormRef.value.validate(async (valid) => {
    if (valid) {
      const result = await assignWorkOrder(assignForm.value);
      if (result.success) {
        ElMessage.success('派单成功');
        assignDialogVisible.value = false;
        resetAssignForm();
        getPageList();
      } else {
        ElMessage.error('派单失败');
      }
    }
  });
};

// 提交收单对话框表单按钮事件
const onReceiveConfirm = async () => {
  if (!receiveFormRef.value) return;
  await receiveFormRef.value.validate(async (valid) => {
    if (valid) {
      const result = await receiveWorkOrder(receiveForm.value);
      if (result.success) {
        ElMessage.success('收单成功');
        receiveDialogVisible.value = false;
        resetReceiveForm();
        getPageList();
      } else {
        ElMessage.error('收单失败');
      }
    }
  });
};

// 删除按钮事件
const handleDelete = (index, row) => {
  ElMessageBox.confirm('确认要删除吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const result = await deleteWorkOrder(row.workOrderId);
      if (result.success) {
        ElMessage.success('删除成功');
        getPageList();
      } else {
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {});
};

// 表单校验
const assignFormRef = ref(null);
const receiveFormRef = ref(null);
const editFormRef = ref(null);

const assignRules = ref({
  workOrderId: [{ required: true, message: '请选择工单', trigger: 'change' }],
  operator: [{ required: true, message: '请选择人员', trigger: 'change' }],
  dispatchTime: [{ required: true, message: '请选择预约安装时间', trigger: 'change' }]
});

const receiveRules = ref({
  workOrderId: [{ required: true, message: '请选择工单', trigger: 'change' }]
});

// 编辑对话框数据和校验规则
const editForm = ref({
  businessId: '',
  status: '',
  dispatchTime: '',
  returnTime: '',
  regionName: ''
});
const editRules = ref({
  businessId: [{ required: true, message: '请输入业务编号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  dispatchTime: [{ required: true, message: '请选择派单时间', trigger: 'change' }],
  returnTime: [{ required: true, message: '请选择返单时间', trigger: 'change' }],
  regionName: [{ required: true, message: '请输入地区', trigger: 'blur' }]
});

// 编辑按钮事件
const handleEdit = async (index, row) => {
  editForm.value = { ...row };
  editDialogVisible.value = true;
};

// 提交编辑对话框表单按钮事件
const onEditConfirm = async () => {
  if (!editFormRef.value) return;
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      const result = await updateWorkOrder(editForm.value);
      if (result.success) {
        ElMessage.success('编辑成功');
        editDialogVisible.value = false;
        getPageList();
      } else {
        ElMessage.error('编辑失败');
      }
    }
  });
};

onMounted(() => {
  getPageList();
});

</script>

<style scoped>
.operation-div {
  width: 100%;
  text-align: left;
  padding-left: 10px;
  padding-top: 10px;
}

.search-div {
  width: 100%;
  text-align: right;
  padding-top: 10px;
}

.dialog-footer {
  text-align: right;
  padding: 10px 0;
}
</style>
